"""
RagFlow 客户端 GUI 文档列表功能模块
"""

from PySide6.QtWidgets import QMessageBox, QVBoxLayout, QHBoxLayout, QTableWidget, QTableWidgetItem, QPushButton, QHeaderView, QWidget
from PySide6.QtWidgets import QWidget as QWidgetContainer

from ragflow_client.gui.features.base_feature import BaseFeature


class DocumentsFeature(BaseFeature):
    """文档列表功能类"""
    
    def __init__(self, parent=None):
        """初始化文档列表功能"""
        super().__init__(parent)
    
    def execute(self):
        """执行文档列表功能"""
        # 验证API配置
        if not self.validate_api_config():
            return
        
        # 创建服务
        service = self.create_service()
        
        # 获取文档列表
        try:
            status, result = service.list_documents()
            if status:
                # 显示文档列表
                documents = result
                if not documents:
                    QMessageBox.information(self.parent, "文档列表", "没有找到文档")
                    return
                
                # 创建内容部件
                content_widget = QWidget()
                layout = QVBoxLayout(content_widget)
                
                # 创建表格
                table = QTableWidget()
                table.setColumnCount(5)
                table.setHorizontalHeaderLabels(["ID", "名称", "大小", "状态", "操作"])
                table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
                table.setRowCount(len(documents))
                
                # 填充表格
                for i, doc in enumerate(documents):
                    table.setItem(i, 0, QTableWidgetItem(doc.get("id", "")))
                    table.setItem(i, 1, QTableWidgetItem(doc.get("name", "")))
                    table.setItem(i, 2, QTableWidgetItem(f"{doc.get('size', 0) / 1024:.2f} KB"))
                    table.setItem(i, 3, QTableWidgetItem(doc.get("status", "")))
                    
                    # 创建操作按钮
                    button_container = QWidgetContainer()
                    button_layout = QHBoxLayout(button_container)
                    
                    # 解析按钮
                    parse_button = QPushButton("解析")
                    doc_id = doc.get("id", "")
                    parse_button.clicked.connect(lambda checked, id=doc_id: self.parse_document(id))
                    button_layout.addWidget(parse_button)
                    
                    # 删除按钮
                    delete_button = QPushButton("删除")
                    delete_button.clicked.connect(lambda checked, id=doc_id, row=i: self.delete_document(id, table, row))
                    button_layout.addWidget(delete_button)
                    
                    button_layout.setContentsMargins(0, 0, 0, 0)
                    table.setCellWidget(i, 4, button_container)
                
                layout.addWidget(table)
                
                # 创建关闭按钮
                close_button = QPushButton("关闭")
                close_button.clicked.connect(lambda: self.window.close())
                layout.addWidget(close_button)
                
                # 创建窗口
                self.window = self.create_window("文档列表", content_widget)
                self.window.show()
            else:
                QMessageBox.critical(self.parent, "错误", f"获取文档列表失败: {result}")
        except Exception as e:
            QMessageBox.critical(self.parent, "错误", f"获取文档列表失败: {str(e)}")
    
    def delete_document(self, document_id: str, table, row: int) -> None:
        """
        删除文档
        
        Args:
            document_id: 文档 ID
            table: 表格部件
            row: 行索引
        """
        # 确认删除
        reply = QMessageBox.question(self.parent, "确认", f"确定要删除文档 {document_id} 吗？", 
                                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply != QMessageBox.Yes:
            return
        
        # 创建服务
        service = self.create_service()
        
        # 删除文档
        try:
            status, result = service.delete_document(document_id)
            if status:
                # 从表格中移除
                table.removeRow(row)
                QMessageBox.information(self.parent, "成功", f"文档删除成功: {document_id}")
            else:
                QMessageBox.critical(self.parent, "错误", f"删除文档失败: {result}")
        except Exception as e:
            QMessageBox.critical(self.parent, "错误", f"删除文档失败: {str(e)}")
    
    def parse_document(self, document_id: str) -> None:
        """
        解析文档
        
        Args:
            document_id: 文档 ID
        """
        parser_id = ""
        
        # 获取解析器ID
        if hasattr(self.parent, "parser_id_edit"):
            parser_id = self.parent.parser_id_edit.text().strip()
        
        # 验证必填字段
        if not parser_id:
            parser_id = "naive"  # 默认解析器
        
        # 创建临时配置和服务
        config = self.create_temp_config(parser_id=parser_id)
        service = self.create_service(config)
        
        # 解析文档
        try:
            status, result = service.parse_document(document_id)
            if status:
                QMessageBox.information(self.parent, "成功", f"文档解析成功: {document_id}")
            else:
                QMessageBox.critical(self.parent, "错误", f"解析文档失败: {result}")
        except Exception as e:
            QMessageBox.critical(self.parent, "错误", f"解析文档失败: {str(e)}")